//
//  CookieManager.swift
//  redbox
//
//  Created by ma c on 2025/9/11.
//

import WebKit

class CookieManager {
    static let shared = CookieManager()
    
    private init() {}
    
    /// 为指定盒子保存Cookie
    func saveCookies(for boxId: UUID, completion: @escaping () -> Void) {
        let cookieStore = WKWebsiteDataStore.default().httpCookieStore
        
        cookieStore.getAllCookies { cookies in
            // 过滤出DNF相关的Cookie
            let dnfCookies = cookies.filter { $0.domain.contains("dnf.qq.com") || $0.domain.contains("qq.com") }
            
            // 保存到Keychain
            SecurityManager.saveCookies(dnfCookies, for: boxId)
            
            completion()
        }
    }
    
    /// 为指定盒子恢复Cookie
    func restoreCookies(for boxId: UUID, to webView: WKWebView, completion: @escaping () -> Void) {
        // 从Keychain加载Cookie
        if let cookies = SecurityManager.loadCookies(for: boxId) {
            let cookieStore = webView.configuration.websiteDataStore.httpCookieStore
            
            // 先清除现有Cookie
            cookieStore.getAllCookies { existingCookies in
                for cookie in existingCookies {
                    cookieStore.delete(cookie)
                }
                
                // 注入保存的Cookie
                for cookie in cookies {
                    cookieStore.setCookie(cookie)
                }
                
                completion()
            }
        } else {
            completion()
        }
    }
    
    /// 清除指定盒子的Cookie
    func clearCookies(for boxId: UUID) {
        SecurityManager.deleteCookies(for: boxId)
    }
    
    /// 清除所有Cookie
    func clearAllCookies() {
        let websiteDataTypes = Set([WKWebsiteDataTypeCookies])
        let date = Date(timeIntervalSince1970: 0)
        
        WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: date) {}
    }
}